﻿using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;


namespace uTools
{
    [AddComponentMenu("uTools/Internal/Drag ObjectAdv(uTools)")]
    public class UDragObjectAdv : MonoBehaviour, IDragHandler
    {
        public int maxX;
        public int minX;
        public int maxY;
        public int minY;
        private float curX;
        private float curY;
        private uTweenPosition tweenPosition;
        public DragDir dragDir = DragDir.XY;

        private void OnDisable()
        {
            if (null != tweenPosition)
                tweenPosition.enabled = false;
        }

        public RectTransform target;

        RectTransform cacheTarget
        {
            get
            {
                if (target == null)
                {
                    target = GetComponent<RectTransform>();
                }
                return target;
            }
        }

        // Use this for initialization
        void Start()
        {

        }

        // Update is called once per frame
        void Update()
        {

        }

        public void OnDrag(PointerEventData eventData)
        {
            Vector3 from = cacheTarget.localPosition;
            Vector3 to = Vector3.zero;
            if (dragDir == DragDir.XY)
                to = from + new Vector3(eventData.delta.x, eventData.delta.y, 0);
            else if (dragDir == DragDir.X)
            {
                curX = eventData.delta.x;
                to = from + new Vector3(curX, 0, 0);
                if (to.x > maxX) to.x = maxX;
                if (to.x < minX) to.x = minX;
            }
            else if (dragDir == DragDir.Y)
            {
                curY = eventData.delta.y;
                to = from + new Vector3(0, curY, 0);

                if (to.y > maxY) to.y = maxY;
                if (to.y < minY) to.y = minY;
            }
            tweenPosition = uTweenPosition.Begin(gameObject, from, to, .02f);//.easeType = EaseType.easeInBack;

            
        }

        
    }
}